package MiddlePractice;

import util.ListNode;

public class Demo19 {
	public static void main(String[] args) {
		
		int[] a1 = {1,2};
		int[] a2 = {0,9,1,5,5,5,1,1,6};
		
		ListNode l1 = new ListNode(a1[0], null);
//		ListNode l2 = new ListNode(a2[0], null);
		ListNode p = l1;
//		ListNode q = l2;
		
		for(int i=1; i<a1.length; i++) {
			p.next = new ListNode(a1[i], null);
			p = p.next;
		}
//		for(int i=1; i<a2.length; i++) {
//			q.next = new ListNode(a2[i], null);
//			q = q.next;	
//		}
		
		
		for(p=l1; p!=null; p=p.next) {
			System.out.print(p.val);
		}
		System.out.println( );
//		for(p=l2; p!=null; p=p.next) {
//			System.out.print(p.val);
//		}
//		System.out.println( );
		
		ListNode ans =  removeNthFromEnd(l1, 2);
		if(ans == null)
			System.out.println("null");
		
		for(p=ans; p!=null; p=p.next) {
			System.out.print(p.val);
		}
	}
	
    static ListNode removeNthFromEnd(ListNode head, int n) {
    	if(head.next == null && n==1)
    		return null;
    	
    	ListNode p,r;
    	
    	p = head;
    	r = null;
    	
    	int i = 0;
    	while(p != null) {
    		
    		if(i == n)
    			r = head;
    		else if(i > n)
    			r = r.next;
    		else
    			r = null;
    		
    		p = p.next;
    		i++;
    	}
    	
    	if(i == n)
    		return head.next;
    	
    	ListNode q = r.next;
    	r.next = q.next;
    	
    	return head;
    }
}
















